﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HandleMessage : MonoBehaviour
{
    public GetHeadsetData head;
    public ReplaceEye eye;
    private System.Net.Sockets.Socket client;
    private byte[] frameByte;
    private string str;
    private Texture2D frame_l;
    private Texture2D frame_r;
    private bool flag;
    IPEndPoint ipep;
    EndPoint ep;
    System.Net.Sockets.Socket socket;

    void Start()
    {
        flag = true;
        frame_l = new Texture2D(476, 476);
        frame_r = new Texture2D(476, 476);
        frameByte = new byte[50 * 1024];
        ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
        ep = (EndPoint)ipep;
        socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        // Thread t = new Thread(new ThreadStart(run));
        // t.Start();
        
        // IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
        // EndPoint ep = (EndPoint)ipep;
        // System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.Bind(ipep);
    }

    void Update()
    {
        byte[] data = new byte[50 * 1024];
        int len = socket.ReceiveFrom(data, ref ep);
        str = Encoding.ASCII.GetString(data, 0, 1);
        Array.Copy(data, 1, frameByte, 0, len - 1);

        if (str == "l") {
            frame_l.LoadImage(frameByte);
            eye.setLframe(frame_l);
        }
        else if (str == "r") {
            frame_r.LoadImage(frameByte);
            eye.setRframe(frame_r);
        }

    }

    void OnDestroy()
    {
        socket.Close();
    }

    void run()
    {
        byte[] data = new byte[50 * 1024];

        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
        EndPoint ep = (EndPoint)ipep;
        System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        socket.Bind(ipep);

        while (flag) {
            int len = socket.ReceiveFrom(data, ref ep);
            str = Encoding.ASCII.GetString(data, 0, 1);
            Array.Copy(data, 1, frameByte, 0, len - 1);
        }

        
    }
}
